package com.bicycle.model;

import com.bicycle.entity.Point;
import com.bicycle.entity.Route;
import com.bicycle.enums.State;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class Lorry {

    private int id;//编号
    private State state;//状态
    private Point point;//坐标
    private Point destination;//目的地
    private int speed;//移动的速度
    private Route route;

    public Lorry(int id, Point pointer){
        this.id=id;
        this.state= State.IDLE;
        this.point = pointer;
    }
    public Lorry(int id, Point pointer,Point destination){
        this.id=id;
        this.state= State.IDLE;
        this.point = pointer;
        this.destination = destination;
    }
    /**
     * 设置小黄车的状态
     * @param state 新状态
     * @param route 路线
     */
    public void setState(State state, Route route){
        if(state== State.MOVING){
            this.speed=3;
        }
        this.state = state;
        this.route=route;
    }
    public State getState(){
        return this.state;
    }

    /**
     * 判断货车是否到达目的地
     * @return
     */
    public boolean isArrived(){
        if(this.route!=null){
            return this.route.isArrived();
        }
        return false;
    }

    /**
     * 决定time时刻小自行车的运动状态
     * @param time 时刻
     */
    public boolean controller(int time){
        if(this.state==State.MOVING)move(time);

        try {
            File file = new File("data", "lorry-" + id);
            FileWriter fileWriter = new FileWriter(file,true);
            fileWriter.write(String.valueOf(time)+','+point.row+','+point.column+','+state+'\n');
//            if(state==State.PEOPLE_RID){
//                System.out.println("--------------------有人骑车----------------"+id);
//            }
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.state == State.IDLE;
    }

    /**
     * 根据路线向上，或下，或左，或右移动一步
     */
    private void moveStep(){
        //先进行到达目的地判断
        if(this.route.isArrived()){
            this.state=State.IDLE;
            //货车到达目的地以后
            return;
        }
        Point next = route.nextNode();
        //每一步只能朝一个方向移动，使用if-else分开
        if(next.row==point.row){
            //上下移动
            this.point.column+=next.column-point.column>0?1:-1;
        }else{
            if(next.column==point.column){
                //左右移动
                this.point.row+=next.row-point.row>0?1:-1;
            }
        }
        //判断是否到达下一个节点
        if(point.row==next.row&&point.column ==next.column){
            route.move();
        }
    }

    /**
     * 每一秒的地移动
     */
    private void move(int time){

        for(int i=0;i<speed;i++){
            this.moveStep();
        }
    }

    public Point getPoint(){
        return this.point;
    }
}
